package lenfs.util;

import java.io.File;

public class FileHandle {

	private int hashExport;
	private int hashRoot;
	private int hashFile;
	private int hash;

	public static FileHandle readFromPacket(final XDR packet) {
		int export = packet.getInt();
		int root = packet.getInt();
		int file = packet.getInt();

		for (int i = 0; i < 5; ++i)
			packet.getUInt();

		return new FileHandle(export, root, file);
	}

	public void infToPacket(final XDR packet) {
		packet.addUInt(hashRoot);
		packet.addUInt(hashFile);
	}

	public void toPacket(final XDR packet) {
		packet.addUInt(hashExport);
		packet.addUInt(hashRoot);
		packet.addUInt(hashFile);

		for (int i = 0; i < 5; ++i)
			packet.addUInt(0);
	}

	protected FileHandle(int export, int root, int file) {
		this.hashFile = file;
		this.hashExport = export;
		this.hashRoot = root;

		this.hash = new String(hashExport + "" + hashRoot + "" + hashFile)
				.hashCode();
	}

	public FileHandle(final int e, final File root, final File file) {
		this.hashFile = new String(file.getAbsolutePath()
				+ System.currentTimeMillis()).hashCode();
		this.hashRoot = root.hashCode();
		this.hashExport = e;
		this.hash = new String(hashExport + "" + hashRoot + "" + hashFile)
				.hashCode();
	}

	public int getExport() {
		return hashExport;
	}

	public String toString() {
		return hashExport + " " + hashRoot + " " + hashFile;
	}

	public int hashCode() {
		return hash;
	}

	public boolean equals(final Object o) {
		if (o == null)
			return false;
		return hash == o.hashCode();
	}
}
